/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.crm.logistic.service.impl.LogisticServiceImpl
   Module Description   :

   Date Created      : 2011/4/8
   Original Author   : cut7man
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.crm.logistic.service.impl;

import java.util.Date;
import java.util.Random;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;

import com.yaodian100.core.admin.entity.Group;
import com.yaodian100.core.admin.entity.User;
import com.yaodian100.core.admin.service.GroupService;
import com.yaodian100.core.admin.service.PermissionService;
import com.yaodian100.core.admin.service.UserService;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.mail.entity.Mail;
import com.yaodian100.core.mail.service.MailService;
import com.yaodian100.crm.logistic.entity.ChangePwdLog;
import com.yaodian100.crm.logistic.service.LogisticService;
import com.yaodian100.crm.workorder.entity.LogisticProvider;

/**
 * @author cut7man
 * 
 */
public class LogisticServiceImpl implements LogisticService {
	@Resource
	private BaseManager baseMgr;
	@Resource
	private UserService userService;
	@Resource
	private GroupService groupService;
	@Resource
	private MailService mailService;
	@Resource
	private PermissionService permissionService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.crm.logistic.service.LogisticService#syncLogisticProvider()
	 */
	@Transactional(readOnly = false)
	public void syncLogisticProvider() {
		Object[] lps = baseMgr.queryByHql("from LogisticProvider", new Object[] {});
		for (Object obj : lps) {
			LogisticProvider lp = (LogisticProvider) obj;

			Group group = (Group) baseMgr.get(Group.class, "L." + lp.getId());
			if (group != null) {
				User user = (User) baseMgr.get(User.class, "L." + lp.getId());
				if (user != null) {
					if (lp.getIsDelete().equals("Y") || lp.getIsEnable().equals("N")) {
						user.setStatus(User.STATUS_INACTIVE);
					} else {
						user.setStatus(User.STATUS_ACTIVE);
					}

					// group.getRole().getPermissions().put("OTHER_LOGISTIC", permissionService.get("OTHER_LOGISTIC"));
					// groupService.update(group);
					userService.update(user);
				}
			} else {
				group = new Group("L." + lp.getId(), lp.getName());
				group.getRole().getPermissions().put("OTHER_LOGISTIC", permissionService.get("OTHER_LOGISTIC"));
				group.setCreateUser("SYSTEM");
				group.setModifyUser("SYSTEM");

				User user = new User("L." + lp.getId());
				user.setNameNative(user.getUsername());
				user.setEmail(lp.getContactEmail());
				String password = createPassword();
				user.setGroup(group);
				if (lp.getIsDelete().equals("N") && lp.getIsEnable().equals("Y")) {
					user.setStatus(User.STATUS_ACTIVE);
				} else {
					user.setStatus(User.STATUS_INACTIVE);
				}
				groupService.save(group);
				userService.createUser(user, password, group.getCode(), false);
				ChangePwdLog cpl = new ChangePwdLog();
				cpl.setUsername(user.getUsername());
				cpl.setChangeDate(new Date());
				baseMgr.save(cpl);
				sendMail(user.getUsername(), password, lp);
			}
		}

	}

	private String createPassword() {
		String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
		int size = str.length();
		StringBuffer sb = new StringBuffer();
		Random ran = new Random();
		for (int i = 0; i < 8; i++) {
			int start = ran.nextInt(size);
			String tmp = str.substring(start, start + 1);
			sb.append(tmp);
		}
		String password = sb.toString();
		return password;
	}

	private void sendMail(String username, String password, LogisticProvider lp) {
		String body = "<html><body>尊敬的合作伙伴，<br/>" + "已为您建立使用者帐号及密码<br/>" + "帐号:" + username + "<br/>" + "密码:" + password
				+ "<br/>" + "若有工单请至http://scm.yaodian100.com/logistic 协助处理<br/>" + "耀点100商业流程开发部 敬上" + "</body></html>";
		try {
			Mail mail = new Mail("create user for upplier", body, lp.getContactEmail(), null);
			mailService.save(mail);
		} catch (CoreException e) {
			throw new RuntimeException(e);
		}
	}
}
